/**
 * @file wa_anim_timeline.c
 *
 */

/*********************
*      INCLUDES
*********************/
#include "wa_anim_timeline.h"
#if USE_WA_ANIM != 0
/*********************
*      DEFINES
*********************/

/**********************
*      TYPEDEFS
**********************/

/**********************
*  STATIC PROTOTYPES
**********************/

/**********************
*  STATIC VARIABLES
**********************/

/**********************
*      MACROS
**********************/

/**********************
*   GLOBAL FUNCTIONS
**********************/

/**
* create a anim timeline
* @param anim timeline
* @param dsc anim dsc array
* @param anim_dsc_cnt how many anim_dsc in anim_timeline
*/
void wa_anim_timeline_init(wa_anim_timeline* anim_timeline, wa_anim_timeline_dsc* dsc, uint32_t anim_dsc_cnt)
{
	anim_timeline->anim_dsc = dsc;
	anim_timeline->anim_dsc_cnt = anim_dsc_cnt;
	anim_timeline->reverse = wa_nok;
}

/**
* create a anim timeline dsc
* @param anim dsc
* @param start_time start time in time line
*/
void wa_anim_timeline_dsc_init(wa_anim_timeline_dsc* dsc, wa_anim* anim, uint32_t start_time)
{
	dsc->anim = anim;
	dsc->start_time = start_time;
}

/**
* set anim timeline reverse
* @param anim timeline
* @param reverse
*/
void wa_anim_timeline_set_reverse(wa_anim_timeline* anim_timeline, wa_result reverse)
{
	anim_timeline->reverse = reverse;
}

/**
* get time long of anim timeline
* @param anim timeline
* @return time long
*/
uint32_t wa_anim_timeline_get_time_long(wa_anim_timeline* anim_timeline)
{
	uint32_t playtime = 0;
	uint32_t i;
	if (anim_timeline->anim_dsc == NULL)
	{
		return 0;
	}
	for (i = 0; i < anim_timeline->anim_dsc_cnt; i++)
	{
		uint32_t end;
		end = wa_anim_get_remain_time(anim_timeline->anim_dsc[i].anim);
		if (end == WA_ANIM_PLAYTIME_INFINITE)
		{
			return end;
		}
		end += anim_timeline->anim_dsc[i].start_time;
		if (end > playtime)
		{
			playtime = end;
		}
	}
	return playtime;
}

/**
* start a anim timeline
* @param anim timeline
* @return how long is the timeline
*/
uint32_t wa_anim_timeline_start(wa_anim_timeline* anim_timeline)
{
	uint32_t i;
	uint32_t playtime = wa_anim_timeline_get_time_long(anim_timeline);
	wa_result reverse = anim_timeline->reverse;
	for (i = 0; i < anim_timeline->anim_dsc_cnt; i++)
	{
		wa_anim* a = anim_timeline->anim_dsc[i].anim;
		uint32_t start_time = anim_timeline->anim_dsc[i].start_time;
		if (reverse == wa_ok)
		{
			int32_t temp = a->start_value;
			a->start_value = a->end_value;
			a->end_value = temp;
			wa_anim_set_delay(a, playtime - (start_time + a->time_long));
		}
		else
		{
			wa_anim_set_delay(a, start_time);
		}
		wa_anim_start(a);
	}
	return playtime;
}

/**********************
 *   STATIC FUNCTIONS
 **********************/

#endif
